<?php

namespace App\Console\Commands;

use App\Models\Phone;
use App\Services\TwilioService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class BuyPhoneNumber extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'console:buy-twilio-phone-number';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '购买Twilio电话号码';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(TwilioService $twilioService,Phone $phone)
    {
        //电话配置
        $setting = DB::table('phone_settings')->where('status',1)->first();
        if($setting && $setting->type == 'twilio'){
            $phones = $phone->whereNull('user_id')->where('phone_setting_id',$setting->id)->get();
            if(count($phones)<5){
                $res = $twilioService->buy();
                $res['phone_setting_id'] = $setting->id;
                $res = Phone::create($res);
                $this->info("购买Twilio电话号码成功！");
            }
        }
    }
}
